package com.msconfig.utils;

/*
 * author: caojunhao
 * date  : 2020/7/6
 * desc  :常用的一些工具
 */

import android.os.Environment;


import com.geo.msconfig.R;
import com.msconfig.MyApplication;
import com.msconfig.event.SaveDataToFileSuccessEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

public class GeneralUtil {

    //保留3位小数
    public static float retain3Point(float data) {
        int beginIndex= Float.toString(data).indexOf(".");
        if(beginIndex==-1){
            return data;
        }
        int lastIndex=beginIndex+4;
        if((lastIndex)> Float.toString(data).length())
            lastIndex= Float.toString(data).length();
        return Float.parseFloat(Float.toString(data).substring(0,lastIndex));
    }


    //把解析好的数据写到文件中
    public static void writeMessageToFile(final String data, final String fileName){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String filePath= Environment.getExternalStorageDirectory()+fileName;
                File file =new File(filePath);
                if(!file.exists()){
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                //如果为追加则在原来的基础上继续写文件
                RandomAccessFile raf = null;
                try {
                    raf = new RandomAccessFile(file, "rw");
                    raf.seek(file.length());
                    raf.write((data).getBytes());
                    EventBus.getDefault().post(new SaveDataToFileSuccessEvent(filePath));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //根据选择的投影模式和当前经度，计算中央经线的值
    public static double autoCalculationCenMeridian(String model,double currentLongitude ) {
        //根据model点击中央经线图标自动获取中央经线
        double autoCentralMeridian;
        if(model.equals(MyApplication.getGlobalContext().getString(R.string.utm_projection))){//UTM投影
            if (currentLongitude < 0)
                autoCentralMeridian = -((int) (-currentLongitude/6) + 0.5)* 6;
            else
                autoCentralMeridian = ((int) (currentLongitude/6) + 0.5) * 6;

        }else{//其他
            // 自动计算三度带的中央子午线，正负分开处理;
            if (currentLongitude < 0)
                autoCentralMeridian = -((int) ((-currentLongitude+1.5)/3)) * 3;
            else
                autoCentralMeridian = ((int) ((currentLongitude+1.5)/3)) * 3;
        }
        return autoCentralMeridian;
    }

}
